package cn.windy.samary.module.shiro.realm;

import cn.windy.samary.module.admin.common.UserLine;
import cn.windy.samary.module.admin.entity.User;
import cn.windy.samary.module.admin.service.IUserService;
import cn.windy.samary.module.shiro.UserTypeToken;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zyl
 * @date 2018/5/6 9:58
 */
public class CustomShiroRealm extends AuthorizingRealm {


    @Resource
    private IUserService userService;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UserTypeToken adminToken = (UserTypeToken) token;
        String username = (String) adminToken.getPrincipal();
        User acc = new User();
        acc.setUsername(username);
        User loginUser = userService.selectOne(acc);
        if (loginUser != null) {
            UserLine userLine = new UserLine();
            userLine.setId(loginUser.getId());
            userLine.setUsername(loginUser.getUsername());
            userLine.setNickname(loginUser.getNickname());
            userLine.setDeptId(loginUser.getDeptId());
            return new SimpleAuthenticationInfo(userLine, loginUser.getPassword(), getName());
        }
        return null;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserLine primaryPrincipal = (UserLine) principals.getPrimaryPrincipal();
        User user = userService.selectByPrimaryKey(primaryPrincipal.getId());
        if (user != null) {
            String userId = user.getId();
            //查询角色
            List<String> roleString = userService.getRoleStringByUserId(userId);
            Set<String> roleStringSet = new HashSet<>(roleString);
            //查询权限
            List<String> permissionString = userService.getPermissionStringByUserId(userId);
            Set<String> permissionStringSet = new HashSet<>();
            for (String perm : permissionString) {
                if (StringUtils.isNotBlank(perm)) {
                    permissionStringSet.addAll(Arrays.asList(perm.trim().split(",")));
                }
            }
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            authorizationInfo.setStringPermissions(permissionStringSet);
            authorizationInfo.setRoles(roleStringSet);
            return authorizationInfo;
        }
        return null;
    }


    /**
     * 清理权限缓存,在动态改变权限后调用，不用重启和重新登陆即可拥有新的权限
     */
    public void clearCachedAuthorizationInfo() {
        //清空权限缓存
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * 清理认证缓存,退出登陆时调用
     */
    public void clearCachedAuthenticationInfo() {
        //清空权限缓存
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        clearCachedAuthenticationInfo(principals);
    }
}
